package com.admin.controller;


import com.admin.dto.UserRoleDTO;
import com.admin.entity.Role;
import com.admin.entity.User;
import com.admin.service.RoleService;
import com.admin.service.UserService;
import com.admin.utils.Result;
import com.admin.vo.query.RoleQueryVo;
import com.admin.vo.query.UserQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Delete;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author szy
 * @since 2023-02-21
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private RoleService roleService;
    /*
    *查询所有用户信息（测试）
    * */
    @GetMapping("/listAll")
    public Result listAll(){
        return Result.ok(userService.list());
    }
    //查询用户列表
    @GetMapping("/list")
    public Result list(UserQueryVo userQueryVo){
        IPage<User> page = new Page<User>(userQueryVo.getPageNo(), userQueryVo.getPageSize());
        userService.findUserListByPage(page,userQueryVo);
        return Result.ok(page);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public Result add(@RequestBody User user){
        User item = userService.findUserByUserName(user.getUsername());
        if (item != null){
            return Result.error().message("学号已存在");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (userService.save(user)){
            return Result.ok().message("用户添加功能");
        }
        return Result.error().message("用户添加失败");
    }

    @PutMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:edit')")
    public Result update(@RequestBody User user){
        User item = userService.findUserByUserName(user.getUsername());
//        if (item != null && item.getUsername() != user.getUsername()){
//            return Result.error().message("学号重复");
//        }
        if (userService.updateById(user)){
            return Result.ok().message("用户修改成功");
        }
        return Result.error().message("用户修改失败");
    }

    @PutMapping("/register")
    public Result register(@RequestBody User user){
        User item = userService.findUserByUserName(user.getUsername());
        if (userService.updateById(user)){
            return Result.ok().message("修改成功");
        }
        return Result.error().message("修改失败");
    }

    /*修改密码*/
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody User user){
        User item = userService.findUserByUserName(user.getUsername());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (userService.updateById(user)){
            return Result.ok().message("密码修改成功");
        }
        return Result.error().message("密码修改失败");
    }

    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@PathVariable Long id){
        if (userService.deleteById(id)){
            return Result.ok().message("用户删除成功");
        }
        return Result.error().message("用户删除失败");
    }

    /*获取分配角色列表*/
    @GetMapping("/getRoleList")
    public Result getRoleList(RoleQueryVo roleQueryVo){
        IPage<Role> page = new Page<Role>(roleQueryVo.getPageNo(), roleQueryVo.getPageSize());
        roleService.findRoleListByUserId(page,roleQueryVo);
        return Result.ok(page);
    }

    /*根据用户id查询该用户拥有的角色列表*/
    @GetMapping("/getRoleByUserId/{userId}")
    public Result getRoleByUserId(@PathVariable Long userId){
        //调用根据用户ID查询该用户拥有的角色ID的方法
        List<Long> roleIds = roleService.findRoleIdByUserId(userId);
        return Result.ok(roleIds);
    }

    /*分配角色*/
    @PostMapping("/saveUserRole")
    @PreAuthorize("hasAuthority('sys:user:assign')")
    public Result saveUserRole(@RequestBody UserRoleDTO userRoleDTO){
        if (userService.saveUserRole(userRoleDTO.getUserId(), userRoleDTO.getRoleIds())){
            return Result.ok().message("角色分配成功");
        }
        return Result.error().message("角色分配失败");
    }

    /*根据角色ID查询用户信息*/
    @GetMapping("/findUserByRoleId")
    public Result findUserByRoleId(Long roleId){
        List<User> users = userService.findUserByRoleId(roleId);
        return Result.ok(users);
    }
}

